package cool.mtc.minghe.service.service;

import com.baomidou.mybatisplus.core.metadata.OrderItem;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import cool.mtc.core.exception.ServiceException;
import cool.mtc.core.page.PageData;
import cool.mtc.core.result.ResultConstant;
import cool.mtc.core.util.StringUtil;
import cool.mtc.minghe.service.manager.sys.dict.DictManager;
import cool.mtc.security.SecuritySupport;
import cool.mtc.web.page.PageHandler;
import lombok.Setter;
import org.springframework.beans.factory.annotation.Autowired;

import javax.servlet.http.HttpServletRequest;
import java.util.HashMap;
import java.util.Map;

/**
 * @author 明河
 */
@Setter(onMethod = @__(@Autowired))
public class BaseServiceImpl implements BaseService, SecuritySupport {
    protected PageHandler pageHandler;
    private HttpServletRequest request;
    private DictManager dictManager;

    public long userId() {
        return Long.parseLong(currentUserId().toString());
    }

    public long orgId() {
        return Long.parseLong(currentUser().getOrgId().toString());
    }

    @Override
    public int getPage() {
        return pageHandler.getPage(request);
    }

    @Override
    public int getPageSize() {
        return pageHandler.getPageSize(request);
    }

    @Override
    public <T> Page<T> pageParam(OrderItem... items) {
        Page<T> pageParam = new Page<>(this.getPage(), this.getPageSize());
        pageParam.addOrder(items);
        return pageParam;
    }

    @Override
    public <T> PageData<T> pageData(Page<T> page) {
        return PageData.of(page.getRecords(), page.getTotal());
    }


    @Override
    public String getDictByKey(String key) {
        Map<String, String> map = dictManager.mapDict();
        return map.get(key);
    }

    @Override
    public String getDictByTypeAndKey(String type, String key) {
        Map<String, String> map;
        switch (type) {
            default:
                map = new HashMap<>();
                break;
        }
        return map.get(key);
    }

    @Override
    public void handleCheckDictExist(long id, String msgArg) {
        String value = this.getDictByKey(Long.toString(id));
        if (StringUtil.isEmpty(value)) {
            throw new ServiceException(ResultConstant.A0400.newInstance().msg("dict.non_exist").args(msgArg));
        }
    }

    @Override
    public void handleCheckDictExist(String type, long id, String msgArg) {
        String value = this.getDictByTypeAndKey(type, Long.toString(id));
        if (StringUtil.isEmpty(value)) {
            throw new ServiceException(ResultConstant.A0400.newInstance().msg("dict.non_exist").args(msgArg));
        }
    }
}
